<?php
/**
* 
*/
class MessageAction extends Action{
public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveimage($postObj);
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }
    
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注微信图书馆";
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }
    
    //接收文本消息
    private function receiveText($object)
    {
        $bstr='还书编号';
        $keyword = trim($object->Content);
        $openid = (string)$object->FromUserName;
        if($keyword=='我要还书'){
           // $map['openid'] = $object->FromUserName;
            $userinfo = M('user')->where(array('openid'=>$openid))->select();
            if($userinfo){
                 $map['wid'] = $userinfo[0]['id'];
                 $map['status'] = 1;
                 $content = '';
                 $ret = M('lendlog')->where($map)->select();
                 if(!$ret){
                    $content = "您还没有借书";
                 }
                    foreach ($ret as $key => $value) {
                       $book = M('book')->where(array('id'=>$value['bid']))->select();
                       $value['book_name'] = $book[0]['book_name'];
                       $content = $content.'编号'.$value['bid'].' 书名'.$value['book_name']." \n";
                    }
             }else{
                $content = '您还没有绑定账号';
             }
            }elseif(strstr($keyword,$bstr)){
                $openid = (string)$object->FromUserName;
                $bid = $this->findNum($keyword);
                $userinfo = M('user')->where(array('openid'=>$openid))->select();
                if($userinfo){
                    $wid = $userinfo[0]['id'];
                    $log = M('lendlog')->where(array('wid'=>$wid,'bid'=>$bid))->select();
                if(empty($log)){
                    $content = "您没有借该书";
                }else{
                    if(empty($log[0]['bqr'])){
                        vendor("PHPQRcode.phpqrcode");
                        $filename ='lend/'.time().'.png'; //图片输出路径和文件名
                        $data='g)bid:'.$bid.',wid:'.$wid;  //接受生成二维码的内容
                        QRcode::png($data, $filename, 'L', 4,2,false);
                        $re['bqr'] = $filename;
                        M('lendlog')->where(array('id'=>$log[0]['id']))->save($re);
                    }else{
                        $filename = $log[0]['bqr'];
                    }
                $content = "请还书时出示链接中的二维码：<a href='http://aaa.17wsx.com/".$filename."'>链接</a>";
                }
            }else{
                    $content = "您还没有绑定账号";
                }
            }else{
                $content = "暂未支持该命令";
            }
        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }
    function findNum($str){
        $str=trim($str);
        if(empty($str)){return '';}
        $result='';
        for($i=0;$i<strlen($str);$i++){
            if(is_numeric($str[$i])){
                $result.=$str[$i];
            }
        }
        return $result;
    }
    private function receiveimage($object)
    {
        $keyword  = trim($object->PicUrl);
        $content = $keyword;
        $result = $this->transmitText($object, $content);
        return $result;
    }
    
    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitNews($object, $arr_item)
    {
        if(!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
        return $result;
    }

    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }

}
?>